﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCPDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SocketServerComm socketServerComm;
        private void Form1_Load(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => {
                DoAction();
            });
           
            btnStop.Enabled = false;
        }

        private void OnMsgEvent(string msg, bool res)
        {
           if (res) {
                richTextBoxPanel1.LogMessage(msg);
            }
           else { richTextBoxPanel1.LogError(msg);}
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                socketServerComm = new SocketServerComm(new SocketServerComm.TcpModule() { LocalIP = "127.0.0.1", LocalPort = int.Parse(txtPort.Text.Trim()) });
                socketServerComm.MsgEvent -= OnMsgEvent;
                socketServerComm.MsgEvent += OnMsgEvent;
                socketServerComm.StartConnection();
                btnConnect.Enabled = false;
                btnStop.Enabled = true;
                txtPort.Enabled = false;

            }catch(Exception ex) { 
             richTextBoxPanel1.LogError(ex.Message);    
            }  
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {

                socketServerComm.StopConnection();
                btnConnect.Enabled = true;
                btnStop.Enabled = false;
                txtPort.Enabled = true;
            }
            catch (Exception ex)
            {
                richTextBoxPanel1.LogError(ex.Message);
            }
        }


        private void DoAction()
        {
            while (true) {

                if (socketServerComm!=null && socketServerComm.IsConnected())
                {
                    socketServerComm.Write(txtPreHead.Text.Trim()+ DateTime.Now.ToString("yyMMddHHmmss"));
                }
                Thread.Sleep(2000); 
            }
        }
    }
}
